const { db, sqlExec } = require('../db/mysql57');

const planDao = {
    /*
     * 获取计划列表
     */
    async getPlanList(uid) {
        let sql = `select
            p.id as id,
            p.title as name,
            p.count as count,
            (select COUNT(*) from PlanCheckin where planId = p.id) as checkinDay,
            (select count(*) from PlanCheckin where planId = p.id and DATE(checkinDate) = CURRENT_DATE()) as isCheckin
        from Plan as p
        where uid = ?`;
        let data = [ uid ];
        return sqlExec(sql, data);
    },
    /*
     * 添加计划
     */
    async addPlan(uid, title, description, count) {
        let sql = `insert into
            Plan(uid, title, description, count)
            values(?, ?, ?, ?)`;
        let data = [uid, title, description, count];
        return sqlExec(sql, data);
    },
    /*
     * 删除计划
     */
    async deletePlan(uid, planId) {
        let sql = `delete from Plan where id = ? and uid = ?`;
        let data = [planId, uid];
        return sqlExec(sql, data);
    },
    /*
     * 修改计划内容
     */
    async updatePlan(uid, planId, title, description, count) {
        let sql = `update Plan set title = ?, description = ?, count = ? where id = ? and uid = ?`;
        let data = [title, description, count, planId, uid];
        return sqlExec(sql, data);
    },
    /*
     * 获取计划详情
     */
    async getPlanInfo(uid, planId) {
        let sql = `select
            p.id as id,
            p.title as name,
            p.description as description,
            p.count as count,
            (select COUNT(*) from PlanCheckin where planId = p.id) as checkinDay,
            (select count(*) from PlanCheckin where planId = p.id and DATE(checkinDate) = CURRENT_DATE()) as isCheckin
        from Plan as p
        where p.uid = ? and p.id = ?
        Limit 1`;
        let data = [uid, planId];
        return sqlExec(sql, data);
    },
    /*
     * 计划打卡
     */
    async checkinPlan(uid, planId, day) {
        let sql = `insert into PlanCheckin(planId, checkinDate)
            select
                ?, ?
            from Plan
            where id = ? and uid = ? and 0 = (
                select count(1)
                from PlanCheckin
                where planId = ? and checkinDate = ?
                LIMIT 1
            )`;
        let data = [planId, day, planId, uid, planId, day];
        return sqlExec(sql, data);
    },
    /*
     * 删除打卡记录
     */
    async deletePlanCheckinRecord(planId) {
        let sql = `delete from PersonalPlanCheckins where planId = ?`;
        let data = [planId];
        return sqlExec(sql, data);
    }
};

module.exports = planDao;